package com.smartwebx.ha.biz.assign.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.base.Splitter;
import com.google.common.collect.FluentIterable;
import com.smartwebx.ha.biz.assign.HaGroupManager;
import com.smartwebx.ha.dal.assign.bean.HaAreaExample;
import com.smartwebx.ha.dal.assign.bean.HaGroup;
import com.smartwebx.ha.dal.assign.bean.HaGroupExample;
import com.smartwebx.ha.dal.assign.dao.HaAreaMapper;
import com.smartwebx.ha.dal.assign.dao.HaGroupMapper;
import com.smartwebx.ha.dal.util.CommonsUtil;
import com.smartwebx.ha.dal.util.MyFunctions;

@Service
public class HaGroupManagerImpl implements HaGroupManager {

	@Autowired
	private HaGroupMapper haGroupDao;
	@Autowired
	private HaAreaMapper haAreaDao;

	@Override
	public List<HaGroup> findAll() {
		HaGroupExample groupExample = new HaGroupExample();
		groupExample.setOrderByClause("id desc");
		List<HaGroup> groups = haGroupDao.selectByExample(groupExample);
		return groups;
	}

	@Override
	public HaGroup findOne(int groupId) {
		return haGroupDao.selectByPrimaryKey(groupId);
	}

	@Override
	public boolean delGroup(String groupIds) {
		HaGroupExample groupExample = new HaGroupExample();
		HaAreaExample areaExample = new HaAreaExample();
		Iterable<String> ids = Splitter.on(",").trimResults().split(groupIds);
		List<Integer> groupIdList = FluentIterable.from(ids)
				.transform(MyFunctions.parseNumberFunctionFor(Integer.class))
				.toList();
		boolean state = false;

		if (groupIdList.isEmpty()) {
			state = true;
		} else {
			groupExample.createCriteria().andIdIn(groupIdList);
			areaExample.createCriteria().andGroupIdIn(groupIdList);
			int state1 = haGroupDao.deleteByExample(groupExample);
			int state2 = haAreaDao.deleteByExample(areaExample);

			if (state1 >= 1 && state2 >= 1) {
				state = true;
			}
		}
		return state;
	}

	@Override
	public boolean addGroup(HaGroup group) {
		int state = haGroupDao.insert(group);
		return CommonsUtil.checkedTrueOrFalse(state);
	}

	@Override
	public boolean updateGroup(HaGroup group) {
		int state = haGroupDao.updateByPrimaryKeySelective(group);
		return CommonsUtil.checkedTrueOrFalse(state);
	}

}
